<template>
  <div id="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图card -->
<el-card class="box-card">
  <div class="search">
    <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear='getUserList'>
      <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
    </el-input>
      <el-button type="primary" class="btn" @click="insertUser">添加用户</el-button>
  </div>
  <!-- 表格区 -->
  <el-table
  border
    :data="usersList"
    style="width: 100%">
    <el-table-column
      type="index"
      label="#"
      width="80">
    </el-table-column>
   <el-table-column
      property="username"
      label="姓名"
      width="240">
    </el-table-column>
     <el-table-column
      property="email"
      label="邮箱"
      width="240">
    </el-table-column>
     <el-table-column
      property="mobile"
      label="电话"
      width="240">
    </el-table-column>
     <el-table-column
      property="role_name"
      label="角色"
      width="240">
    </el-table-column>
     <el-table-column
      property="mg_state"
      label="状态"
      width="240">
      <!-- 状态 -->
      <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state" @change="changeSwith(scope.row)">
          </el-switch>
        </template>
    
    </el-table-column>
    <el-table-column label="操作" width="357">
      <template slot-scope="scope">
        <!-- enterable方法提示文字离开隐藏 -->
          <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
        <el-button type="primary"  size="mini" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete(scope.$index, scope.row)"></el-button>
           </el-tooltip>
            <el-tooltip class="item" effect="dark" content="权限" placement="top" :enterable="false">
          <el-button
          size="mini"
          type="warning"
          icon="el-icon-share"
          @click="UsersRoles(scope.row)"></el-button>
           </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
<!-- 分页区 -->
 <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
  <!-- 弹出添加用户对话框 -->
<el-dialog title="新增用户" :visible.sync="dialogFormVisible">
  <el-form :model="addForm" class="demo-ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
    <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
      <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
    </el-form-item>
   <el-form-item
    prop="email"
    label="邮箱"
    :label-width="formLabelWidth"
  >
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
      <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offForm">取 消</el-button>
    <el-button type="primary" @click="sureForm">确 定</el-button>
  </div>
</el-dialog>
  <!-- 弹出修改用户对话框 -->
<el-dialog title="修改用户" :visible.sync="editFormVisible">
  <el-form :model="editForm" class="demo-ruleForm" :rules="rules" ref="ruleFormEdit" label-width="100px">
    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
    <el-input v-model="editForm.username" :disabled="true"></el-input>
  </el-form-item>
   <el-form-item
    prop="email"
    label="邮箱"
    :label-width="formLabelWidth"
  >
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
      <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offEdit">取 消</el-button>
    <el-button type="primary" @click="sureEdit">确 定</el-button>
  </div>
</el-dialog>
 <!-- 弹出分配权限用户对话框 -->
<el-dialog title="分配权限" :visible.sync="distributionRoles" @close='setDialog'>
  <div style="margin-bottom:15px">当前的用户：{{userInfo.username}}</div>
  <div style="margin-bottom:15px">分配的角色：{{userInfo.role_name}}</div>
    分配新角色：<el-select placeholder="请选择活动区域" v-model="selectRoles">
      <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
    </el-select>
  <div slot="footer" class="dialog-footer">
    <el-button @click="offSoles">取 消</el-button>
    <el-button type="primary" @click="sureSoles">确 定</el-button>
  </div>
</el-dialog>
</el-card>

  </div>
</template>

<script>
export default {
  data(){
    return{
      inputVaule:'',
      // 接口需要的参数
      queryInfo:{
        query:'',
        // 当前的页数
        pagenum: 1,
        // 每页显示2条数据
        pagesize:2,
        total:0
      },
      usersList:[],
      total:0,
      dialogFormVisible: false,
      editFormVisible:false,
      distributionRoles:false,
      addForm: {
          username: '',
          mobile: '',
          email:'',
          password:''
        },
        editForm:{},
        rules:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          mobile: [
          // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/，验证手机号是否正确
          { required: true, message: '请输入手机号', trigger: 'change' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' }
        ],
        },
        formLabelWidth: '70px',
        // 分配权限弹窗的用户信息
        userInfo:{},
        //所有下拉框角色的列表
        rolesList:[],
        selectRoles:''
    }
  },
  created(){
    this.getUserList()
  },
  methods:{
    async getUserList(){
      const { data: res }=await this.$http.get('users',{params:this.queryInfo});
      this.usersList=res.data.users
      this.total=res.data.total
      console.log(res);
    },
    // 编辑删除权限方法
    async handleEdit(index, row) {
      this.editFormVisible = true;
      let id=row.id
      const {data:res}=await this.$http.get(`users/`+id)
      if(res.meta.status!==200) return this.$message.error('查询用户失败')
      this.editForm=res.data
        // console.log(index, row);
      },
      handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {

  

          const { data:res }=await this.$http.delete(`users/${row.id}`)
          if(res.meta.status === 200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUserList()
          }
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        // console.log(index, row);
        
      },
      // 表格方法
      handleSizeChange(val){
        this.queryInfo.pagesize=val;
        this.getUserList()
      },
      handleCurrentChange(val){
        this.queryInfo.pagenum=val;
        this.getUserList()
      },
      // 监听状态开关,以至于点击刷新保持当前状态
      async changeSwith(val){
        const {data:res}=await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
        if(res.meta.status!==200){
            val.mg_state=!val.mg_state
            return this.$message.error('更新状态失败')
        }else{
          this.$message.success('更新状态成功')
        }
      },
      // 打开对话框
      insertUser(){
        this.dialogFormVisible = true;
      },
      // 添加取消对话框后，再打开对话框内容全部清除重新输入
      offForm(){
        this.dialogFormVisible = false;
        this.$refs.ruleForm.resetFields()
      },
      // 添加对话框确定按钮
      sureForm(){
        // 点击确定按钮验证输入框是否输入
        this.$refs.ruleForm.validate(async valid=>{
          if(!valid) return
          // 发送添加请求
          const {data:res}=await this.$http.post('users',this.addForm)
          if(res.meta.status!==201){
            this.$message.error('添加失败')
          }else{
             this.$message.success('添加成功')
             this.dialogFormVisible = false;
            //  重新获取用户列表
            this.getUserList()
          }
        })
      },
       // 修改取消对话框后，再打开对话框重置
       offEdit(){
        this.editFormVisible = false;
         this.$refs.ruleFormEdit.resetFields()
      },
      // 修改对话框确定按钮
      sureEdit(){
        // 点击确定按钮验证输入框是否输入
        this.$refs.ruleFormEdit.validate(async valid=>{
          if(!valid) return
          // 发送添加请求
          const {data:res}=await this.$http.put(`users/${this.editForm.id}`,{email:this.editForm.email,mobile:this.editForm.mobile})
          
          if(res.meta.status!==200){
            this.$message.error('修改失败')
          }else{
             this.$message.success('修改成功')
             this.editFormVisible = false;
            //  重新获取用户列表
            this.getUserList()
          }
        })
      },
      //分配权限
      async UsersRoles(userInfo){
        this.userInfo=userInfo
        const {data:res}=await this.$http.get('roles')
        if(res.meta.status!==200){
          return this.$$message.error('获取角色列表失败')
        }
        this.rolesList=res.data
        this.distributionRoles=true
      },
      offSoles(){
        this.distributionRoles=false
      },
      async sureSoles(){
        //判断用户下拉框有没有选择新的角色
        if(!this.selectRoles){
          return this.$message.error('请选择新的角色')
        }
        const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoles})
        if(res.meta.status!==200){
          return this.$message.error('更新角色失败')
        }
        this.$message.success('更新角色成功')
        this.getUserList()
        this.distributionRoles=false
      },
      //再次打开分配权限对话框刷新
      setDialog(){
        this.selectRoles='',
        this.userInfo={}
      }
  }
}
</script>

<style lang="less" scoped>
#users{
  .box-card{
    margin-top: 20px;
    .search{
      .el-input-group{
        width: 20%;
      }
      .btn{
        margin-left: 25px;
      }
    }
    .el-table{
      margin: 20px 0;
    }
  }
}
</style>